import router, { constantRoutes } from '@/router';
import Layout from '@/Layout/index.vue';
import ParentView from '@/components/ParentView/index.vue';
import { RouterRecord } from "@/global/record/RouterRecord";
import MicroApp from '@/views/microApp/index.vue'
// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../../views/**/*.vue')

export const usePermissionStore = defineStore(
    'permission',
    () => {
      const activeSys = ref<SysRecord>(null);

      const sysList = ref<SysRecord[]>([]);

      const sysMap = ref({});

      const routes = ref<RouterRecord[]>([]);

      const addRoutes = ref<RouterRecord[]>([]);

      const defaultRoutes = ref<RouterRecord[]>([]);

      const topbarRouters = ref<RouterRecord[]>([]);

      const sidebarRouters = ref<RouterRecord[]>([]);

      const sidebarBasePath = ref('');

      function setActiveSys(sys: SysRecord) {
        activeSys.value = sys;
      }

      function setSysList(sysArr: SysRecord[]) {
        sysList.value = sysArr;
      }

      function setSysMap(sysObj) {
        sysMap.value = sysObj;
      }

      function setRoutes(routeList: RouterRecord[]) {
        addRoutes.value = routeList;
        routes.value = constantRoutes.concat(routeList);
      }

      function setDefaultRoutes(routeList: RouterRecord[]) {
        defaultRoutes.value = constantRoutes.concat(routeList)
      }

      function setTopbarRoutes(routeList: RouterRecord[]) {
        topbarRouters.value = routeList
      }

      function setSidebarRouters(routeList: RouterRecord[]) {
        sidebarRouters.value = routeList
      }

      function setSidebarBasePath(basePath: string) {
        sidebarBasePath.value = basePath;
      }

      function generateRoutes() {
        // 向后端请求路由数据
        return getRoutersApi().then(res => {

          let sysRouterList = getSysRouter(res.data);

          let activeSys = getActiveSys(location.pathname, res.data) || res.data[0];

          let sysMap = {};

          let sysList = [];

          res.data.forEach(item => {
            sysMap[item.location] = item.routers
            sysList.push({
              id: item.id,
              title: item.title,
              icon: item.icon,
              location: item.location,
            })
          })

          let touters = sysMap[activeSys.location];

          const sdata: RouterRecord[] = JSON.parse(JSON.stringify(touters))

          const rdata: RouterRecord[] = JSON.parse(JSON.stringify(sysRouterList))

          const sidebarRoutes = filterAsyncRouter(sdata)

          sidebarRoutes.forEach(item => {
            item.path = activeSys.location + item.path;
          })

          const rewriteRoutes = filterAsyncRouter(rdata, false, true);

          setActiveSys(activeSys);
          setSysList(sysList);
          setSysMap(sysMap);
          setRoutes(rewriteRoutes)
          setSidebarRouters(constantRoutes.concat(sidebarRoutes))
          setDefaultRoutes(sidebarRoutes)
          setTopbarRoutes(sidebarRoutes)

          return rewriteRoutes
        })
      }

      return {
        activeSys,
        sysList,
        sysMap,
        routes,
        addRoutes,
        defaultRoutes,
        topbarRouters,
        sidebarRouters,
        setRoutes,
        setDefaultRoutes,
        setTopbarRoutes,
        setSidebarRouters,
        sidebarBasePath,
        setSidebarBasePath,
        generateRoutes,
      }
    }
)

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap: RouterRecord[], lastRouter: RouterRecord | boolean = false, type = false) {
  return asyncRouterMap.filter(route => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }

    if (route.hidden) {
      const pathFirst = route.path.split('/').shift()
      if (pathFirst && route.component.includes(pathFirst)) {
        const compFirst = route.component.split(pathFirst).shift()
        if (compFirst) {
          route.meta['activeMenu'] = '/' + compFirst + pathFirst;
        }
      }
    }
    if(route.meta){
      route.meta['isMicroApp'] = true
    }

    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else {
        route.component = MicroApp // loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter: any = false) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView' && !lastRouter) {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
      if (el.children && el.children.length) {
        children = children.concat(filterChildren(el.children, el))
        return
      }
    }
    children = children.concat(el)
  })
  return children
}

export const loadView = (view) => {
  let res;
  for (const path in modules) {
    const dir = path.split('views/')[1].split('.vue')[0];
    if (dir === view) {
      res = () => modules[path]();
    }
  }
  return res;
}


/**
 *
 * @param SysRouters 系统路由
 * @returns {[sysRoutersList]}
 */
function getSysRouter(SysRouters) {
  let sysRoutersArr = JSON.parse(JSON.stringify(SysRouters))
  let sysRoutersList = []
  sysRoutersArr.forEach(item => {
    item.routers.forEach(item2 => {
      if (item2.component == "Layout") {
        item2.component = "ParentView"
      }
      item2.path = item2.path.replace("/", "")
    })
    let routerItem = {
      path: item.location,
      name: item.location,
      mode: item.location,
      title: item.title,
      component: "Layout",
      children: item.routers,
    }
    sysRoutersList.push(routerItem);
  })
  // SysRouters
  return sysRoutersList;
}


//获取激活系统
function getActiveSys(pathname, sysList) {
  let baseUrl = ""
  // baseUrl.replaceAll()
  let urlItems = pathname.split("/");
  if (urlItems.length > 1) {
    baseUrl = urlItems[1];
  }
  let activeSys = sysList.find(item => {
    let locationUrl = item.location.replaceAll("/", "")
    if (locationUrl == baseUrl) {
      return item
    }
  })
  return activeSys;
}